package com.sky.service.impl;



import com.sky.dto.SalesTop10ItemDTO;
import com.sky.mapper.ReporMapper;
import com.sky.service.OrderService;
import com.sky.service.ReporService;
import com.sky.service.UserService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReporServiceImpl implements ReporService {
    @Autowired
    ReporMapper reporMapper;
    @Autowired
    OrderService orderService;
    @Autowired
    UserService userService;
    /**
     * 营业额
     * **/
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 生成x轴的时间数据
        List<LocalDate> dateList = new ArrayList<>();
        while(begin.isBefore(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        // 遍历每一天，查询当天的订单已经完成的金额
        List<Double> turnOverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            // startTime：就是年月日00:00:00
            LocalDateTime startTime = LocalDateTime.of(localDate, LocalTime.of(0, 0, 0));
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.of(23, 59, 59));
            double turnOver = orderService.turnOver(startTime, endTime);
            turnOverList.add(turnOver);
        }
        // 组装结果数据
        TurnoverReportVO vo = new TurnoverReportVO();
        vo.setDateList(
                dateList.stream()
                        .map(date->date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .collect(Collectors.joining(",")));
        vo.setTurnoverList(
                turnOverList.stream()
                        .map(turnOver->String.valueOf(turnOver))
                        .collect(Collectors.joining(","))
        );
        return vo;
    }

    /**
     * 用户统计
     * */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //生成x轴的时间数据
        List<LocalDate> dateList = new ArrayList<>();
        while (begin.isBefore(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        //遍历每一天，查询新用户 和总用户数量
        StringBuilder newUsers = new StringBuilder();
        StringBuilder totalUsers = new StringBuilder();
        for (LocalDate localDate : dateList) {
            //当天开始时间
            LocalDateTime startTime = LocalDateTime.of(localDate, LocalTime.of(0, 0, 0));
            //当天终止时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.of(23, 59, 59));
            //查询新用户数量
            int newUserCount = userService.contNewUser(startTime,endTime);
            //查询截止到当前时间总的用户数量
            int totalUserCount = userService.countTotalUser(endTime);
            //构造拼接数据
            if (newUsers.length()>0){
                newUsers.append(",");
            }
            newUsers.append(newUserCount);
            if (totalUsers.length()>0){
                totalUsers.append(",");
            }
            totalUsers.append(totalUserCount);
        }
         //封装vo返回
        UserReportVO vo = new UserReportVO();
        vo.setDateList(
                dateList.stream()
                        .map(date->date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .collect(Collectors.joining(","))
        );
        vo.setNewUserList(newUsers.toString());
        vo.setTotalUserList(totalUsers.toString());
        return vo;
    }
    /**
     * 订单统计
     * */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //生成x轴的时间数据
        List<LocalDate> dateList = new ArrayList<>();
        while (begin.isBefore(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        //总的订单数
        int total = 0;
        //总的有效订单数
        int totalValid = 0;
        //每天的总订单数
        List<Integer> dayTotalList = new ArrayList<>();
        //每天的有效订单数
        List<Integer> dayValidList = new ArrayList<>();
        //遍历每一天
        for (LocalDate localDate : dateList) {
            //当天的开始时间
            LocalDateTime startTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //当天的结束时间
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询当天的订单总数
       int dayTotal  =  orderService.countTotalOrders(startTime,endTime);
            //查询当天的有效订单
       int dayValid = orderService.countValidOrders(startTime,endTime);
            //保存到list
            dayTotalList.add(dayTotal);
            dayValidList.add(dayValid);
            //累加到合计
            total += dayTotal;
            totalValid += dayValid;
        }
        //封装返回vo
        OrderReportVO vo = new OrderReportVO();
        vo.setValidOrderCount(totalValid);
        vo.setTotalOrderCount(total);
        vo.setOrderCompletionRate(totalValid * 1.0/ total);
        vo.setDateList(join(dateList));
        vo.setValidOrderCountList(join(dayValidList));
        vo.setOrderCountList(join(dayTotalList));
        return vo;
    }

    private <T> String join(List<T> list){
        return list.stream().map((e)->String.valueOf(e)).collect(Collectors.joining(","));
    }
    /**
     * 销量排名
     * */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<SalesTop10ItemDTO> list =orderService.top10(begin,end);
        //封装成SalesTop10ReportVO
        SalesTop10ReportVO vo = new SalesTop10ReportVO();
        //获取名称
        String names = list.stream().map(SalesTop10ItemDTO::getName).collect(Collectors.joining(","));
        vo.setNameList(names);
        //获取销售数量
        String numbers = list.stream().map(SalesTop10ItemDTO::getSale).map(e -> String.valueOf(e)).collect(Collectors.joining(","));
        vo.setNumberList(numbers);
        return vo;
    }
}
